/// 澄西调度系统

#include <iostream>
#include <sqlite3.h>
#include "io/WrlInfo.h"
#include "io/FileOp.h"
#include "io/AppConfig.h"
#include "CXScheduler.h"
#include "dd/CombineJoint.h"

#include "io/StartProcess.h"

static std::string getLastPartAfterSlash(const std::string& path) {
    // 查找最后一个斜杠的位置
    size_t lastSlashPos = path.find_last_of('/');

    if (lastSlashPos == std::string::npos) {
        // 如果没有找到斜杠，返回整个字符串
        return path;
    } else {
        // 返回最后一个斜杠之后的内容
        return path.substr(lastSlashPos + 1);
    }
}


/** 生成小严的程序
 *  path: 胡博所有的wrl信息，绝对路径
 **/
void StartALLWRL(const std::string &path)
{
    std::string app = "GenStep";
    std::string arg = "dir";

    auto dirPant = GetCurrentDir();
    createDirectories(dirPant + "/Plan/runData");
    // clearFolderContents(dirPant + "/Plan/runData");
    createDirectories("Plan/runData");

    WRLJsonMap m_maps = loadWRLJsonMapFromFile(path);

    DBStructMap target;  //** 简单的中转数据，存放的是小严结构的轴数据 **//
    for(const auto& a: m_maps){

        WrlInfo info;
        info.GetDataByHubo(a.second);
        // TODO

//        std::cout << "Start APP:" << info.current_path <<'\t'
//                     << info.name << '\t'
//                        << info.index  << '\t' << info.workID << std::endl;

        std::vector<std::pair<std::string, std::vector<std::string>>> processes_to_start = {
            {"./CXPlan", {info.current_path, "0",std::to_string(info.index)}},
            {"./CXPlan", {info.current_path, "1",std::to_string(info.index)}},
            {"./CXPlan", {info.current_path, "2",std::to_string(info.index)}}
        };

//        for(auto &process:processes_to_start){
//            StartProcess::start_process(process.first, process.second);
//        }
#if RUN_APP
         StartProcess::run_concurrent_processes(processes_to_start,4);
#endif
        // std::cout << "Dir: " << a.second.dir_path << std::endl;
        /** 执行完成后的动作 **/
        target[a.first].path = a.second.dir_path;
        target[a.first].workID = a.second.wrlid;
        target[a.first].name = info.name;

        std::string diban,han,Loader,unLoader;
        if(1 == info.workID)
        {
            diban = "plateScan";
            han = "hanL";
            Loader = "LoaderL";
            unLoader = "unLoaderL";
        }else
        {
            diban = "plateScan";
            han = "hanR";
            Loader = "LoaderR";
            unLoader = "unLoaderR";
        }
        target[a.first].diban_json = dirPant + "/Plan/runData/" + info.name + "/" + diban + ".json";
        target[a.first].mhd_json = dirPant + "/Plan/runData/" + info.name + "/" + han + ".json";
        target[a.first].up_json = dirPant + "/Plan/runData/" + info.name + "/" + Loader + ".json";
        target[a.first].down_json = dirPant + "/Plan/runData/" + info.name + "/" + unLoader + ".json";
        target[a.first].index = a.first;

        target[a.first].partALL = a.second.partCount;
    }
    to_json("Plan/runData/xxxxx.json",target);
}

/**
 *  StartALLWRL 执行后会生成一个json文件，存储信息和轨迹
 *
**/
void SortAL(const AppConfig &config)
{
    /** 需要先根据工件顺序一次排好轨迹 **/
    DBStructMap mtar;
    from_json("Plan/runData/xxxxx.json",mtar);
    std::vector<OneWrlInfo> wrls;
    for(const auto &a:mtar){
        DBStruct sd = a.second;

        if(sd.workID % 2 == 1){
            OneWrlInfo sA("SA", sd.name, sd.workID);
            sA.CreateScanJoint(sd.diban_json);
            sA.CreateWeldJoint(sd.mhd_json);
            sA.CreateUpJoint(sd.up_json);
            sA.CreateDownJoint(sd.down_json);
            wrls.push_back(sA);
        }else{
            OneWrlInfo sB("SB", sd.name, sd.workID);
            sB.CreateScanJoint(sd.diban_json);
            sB.CreateWeldJoint(sd.mhd_json);
            sB.CreateUpJoint(sd.up_json);
            sB.CreateDownJoint(sd.down_json);
            wrls.push_back(sB);
        }
    }


    // 创建调度器
    Scheduler scheduler(wrls);

    sch.ch1Real = config.stn1;
    sch.ch2Real = config.stn2;
    sch.chAssReal = config.assm;
    sch.chUp = config.up;
    sch.chDown = config.down;
    sch.moniCount = config.moniCount;

    scheduler.createAllTasks();

    // 调度所有任务
    scheduler.scheduleAllTasks();
}


int main(int argc, char *argv[])
{
    //GetCurrentDir(true);

    AppConfig config;
    from_json("conf/config.json",config);

    std::cout << "argc==> " << argc  << std::endl;
    {
        StartALLWRL("runDB/HuSerial.json");

        SortAL(config);
        logger.Close();
    }

     CombineJoint com;
     com.Start("task_log.csv");
     com.SerialALL();

    return 0;
}
